package com.lagou.edu.factory;

import com.lagou.edu.annotation.Autowired;
import com.lagou.edu.annotation.Service;
import com.lagou.edu.utils.TransactionManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//负责实现事务控制
@Service("proxyFactroy")
public class ProxyFactroy  {
    @Autowired
    private TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }


    public Object getProxy(Object target){
        Object proxy =Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object result = null;
                try{
                    System.out.println("开始事务");
                    transactionManager.beginTransaction();
                    result = method.invoke(target,args);
                    transactionManager.commit();
                    System.out.println("事务提交");
                }catch (Exception e){
                    e.printStackTrace();
                    System.out.println("捕捉到错误，数据库回滚");
                    transactionManager.rollback();
                    throw e;
                }

                return result;
            }
        });
        return proxy;
    }
}
